package day19;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectPrc2 {
    @Test
    public void ReflectTest2() throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class<?> s1=Person.class;
        Field dF = s1.getDeclaredField("name");
        Field[] dFs = s1.getDeclaredFields();
        for (Field f:dFs){
            System.out.println(f);
        }
        /**暴力获取私有所有成员变量不需要设置权限*/
        dF.setAccessible(true);
        System.out.println(dF.getType().getName());
        System.out.println(dF.getName());
        Object o = s1.newInstance();
        dF.set(o,"张大喵");
        System.out.println(dF.get(o));
    }
    /**暴力反射获取方法*/
    @Test
    public void getMs() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Class<?> s1=Person.class;
//        Method[] dMs = s1.getDeclaredMethods();
//        for (Method m:dMs){
//            System.out.print(m+",,,");
//            System.out.println(m.getName());
//        }
        Method method = s1.getDeclaredMethod("find", String.class);
        method.setAccessible(true);
        /**使用方法前需要实例化*/
        Object obj = s1.newInstance();
        Object find = method.invoke(obj, "好的");
    }
    /**实例化私有成员变量的类*/
    @Test
    public void NewIns() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
        Class<?> s1=Person.class;
        Constructor<?> dCons = s1.getDeclaredConstructor(String.class, int.class);
        dCons.setAccessible(true);
        Object obj = dCons.newInstance("张大喵", 25);
        System.out.println(obj);
        Person person1=(Person) obj;
        Field f1 = s1.getDeclaredField("name");
        Field f2 = s1.getDeclaredField("age");
        f1.setAccessible(true);
        f2.setAccessible(true);
        System.out.println(f1.get(obj)+","+f2.get(obj));
        f1.set(obj,"李云龙");
        f2.set(obj,30);
        System.out.println(f1.get(obj)+","+f2.get(obj));
        System.out.println(obj);
    }

}
